#!/usr/bin/env node
const program = require('commander');
const _ = require("lodash");
const moment = require("moment");
const utils = require('./js/utils');

function main() {
    program
        .version('0.0.1')
        .option('-s, --seperator [空格|，|,|；|;|、]', '分隔符')
        .option('-m, --multiline', '多行使用 \\r?\\n 分割，否则使用分隔符 + \\r?\\n 分割')
        .option('-r, --rowformat [parseFunction|#n...#m]', `遵循parseFunction入参为row,否则取第n,m列的数据组合，只对多行有效`)
        .option('-f, --format [parseFunction]', '遵循parseFunction入参为item')
        .option('-o, --outformat [""]', '"": 原始值, 0: js 1: json 2:inline-js 3:inline-json', '0')
        .option('-c, --copy', '拷贝到clipboard')
        .option('\nxsplit -m -r 0 => 1 2\\n3 4 -> 1\\n3')
        .option('xsplit -m -r #0:#1 => 1 2\\n3 4 -> 1:2\\n3:4')
        .option('xsplit -m -r (list, {_, moment, utils})=>[]')
        .option('xsplit -f =$123')
        .option('遇到箭头函数必须用引号')
        .parse(process.argv);

    let { seperator, multiline, rowformat, format, outformat, copy } = program;
    if (!multiline && rowformat) {
        return console.log('rowformat只针对多行有效');
    }
    const sep = seperator ? seperator : '，,；;、';
    utils.paste(async text => {
        let rows;
        format = utils.parseFunction(format, 1);
        if (multiline) {
            rows = text.split(/\r?\n/).map(o => o.split(new RegExp(seperator ? sep.split('').join('|') : sep.split('').concat('\\s+').join('|'))));
            if (rowformat) {
                rowformat = utils.parseFunction(rowformat, 1);
                if (_.isFunction(rowformat)) {
                    rows = rows.map(o => rowformat(o, { _, moment, utils }));
                } else {
                    let matches = rowformat.match(/\#\d+/g);
                    rows = rows.map(row => matches.reduce((r, n) => r.replace(n, row[n.substr(1)]), rowformat));
                }
            }
            if (_.isFunction(format)) {
                rows = rows.map(row => row.map(o => format(o, { _, moment, utils })));
            }
        } else {
            rows = text.split(new RegExp(seperator ? sep.split('').join('|') : sep.split('').concat('\\s+').concat(`\\r ?\\n`).join('|')));
            if (_.isFunction(format)) {
                rows = rows.map(o => format(o, { _, moment, utils }));
            }
        }
        if (outformat === '') {
            if (_.isArray(rows[0])) {
                rows = _.reduce(rows, (r, m) => [...r, m.join(' ')], []).join('\n');
            } else if (multiline) {
                rows = rows.join('\n');
            } else {
                rows = rows.join(' ');
            }
        } else {
            rows = utils.stringify(rows, +outformat);
        }
        copy && utils.copy(rows);
        console.log(rows);
    });
}
main();
